<?php
/**
 * Created by PhpStorm.
 * User: zhangshiping
 * Date: 15-12-7
 * Time: 下午6:19
 *
 */

namespace Common\Logic;


class KmiCronLogic {
    private $log = ''; //错误日志文件,路径
    protected $daytoprice=array(); //缓存当天单价
    protected  $videoCount = array(); //影片点播统计
    protected $DbType = array(); //数据库链接标记
    protected $billing_time = 900; //版权计费节点15分钟，C('BILLING_BASE')是K米的计费节点
    protected $configs = [];
    public function __construct(){
        //$this->billing_time = C('BILLING_BASE');//K米的计费节点
    }

    //统计计费开始时间
    private function billingStartInfo($nearTime,$type){
        $coutInfo = array(); //每天的影厅数量
        $step_price = array(); //阶梯价格
        $now = strtotime(date('Y-m-d 00:00:00',NOW_TIME)); //统计到前一天的数据
        for($i=$nearTime;$i<$now;$i +=3600*24){
            $res = $this->getPrice($i,$type);
            $price = $res['price'];
            $coutInfo[$i] = array(
                'price'=>$res['price'], //当日计算价格
                'count'=>$res['total'], //当日影厅数量
                'time'=>$i //date('Y-m-d H:i:s',$i) //时间
            );
            if(!isset($starprice) || $starprice!=$price){
                $starprice = $price;
                $step_price[] = array('start'=>$i,'end'=>$i+3600*24-1,'price'=>$price); //第一个阶梯价
            }
            $step_price[count($step_price)-1]['end'] = $i+3600*24-1;
        }
        return array('coutInfo'=>$coutInfo,'step_price'=>$step_price);
    }

    /**
     * 获取当天单价
     */
    private function getPrice($time,$type){
        $day = $time-(($time-$this->timediff)%86400); //当天时间
        if(!$this->daytoprice[$day]){ //获取当天单价
            $sql = 'SELECT `price`,`total` FROM '.trueTab('OrgHallCount').' WHERE `day` <='.$day.' AND `type`='.$type.' ORDER BY `id` DESC LIMIT 1;';
            $res = M()->db(0)->query($sql);
            $price = $res[0]['price'] ? $res[0]['price'] : current(C('BILLING_RULE'.$type));
            $this->daytoprice[$type][$day]['price'] = $price ? $price : 1; //单价，如果没定义，设为1，展示“有效”播放数据
            $this->daytoprice[$type][$day]['total'] = $res[0]['total'] ? $res[0]['total'] : 0; //屏幕总数
        }
        return $this->daytoprice[$type][$day];
    }



    /**
     * 增量统计每天影院消费数据
     */
    protected function countCinema(){
        $cinemas = D('Common/Cache','Logic')->HGETALL(C('DATA_KEY.CHANGE_CINEMA')); //查询所有有数据变动的kmi影院
        $top = C('EXTREMITY_COST');
        $cinema_count = array(); //统计数据
        $film_count = array();
        $now = strtotime(date('Y-m-d 00:00:00',NOW_TIME))-1; //统计截止时间
        //统计影院
        foreach($cinemas as $host_name=>$row){
            //获取影院类型
            $type = $this->getCinemaType($host_name);
            $this->connect($type); //初始化分库链接
            //查询最新一次播放修改记录
            $sql = 'SELECT * FROM '.trueTab('OrgPlay_'.$row).' WHERE `status`<>2 ORDER BY `play_start` LIMIT 1;';
            $near = M()->db($type)->query($sql);
            $near = $near[0];
            if(!$near){continue;}
            $nearTime = strtotime(date('Y-m-d 00:00:00',$near['play_start'])); //统计开始时间
            $res = $this->billingStartInfo($nearTime,$type);
            foreach($res['step_price'] as $value){ //跨单价计费统计
                $price = $value['price'] ? $value['price'] : 0.1; //未设置单片全价
                $sql = "SELECT FROM_UNIXTIME(play_start,'%Y-%m-%d') AS `day`,hall_id,
                              (CASE WHEN SUM(pay)>{$top} THEN {$top} ELSE SUM(pay) END) AS `pay`,SUM(`pay`) AS total_price,COUNT(`id`) AS play_count,
                            SUM((pay=".($price/2).")) AS play_half_billing,
                        SUM((pay={$price})) AS play_all_billing
                    FROM ".trueTab('OrgPlay_'.$row)."
                    WHERE `play_start` BETWEEN {$value['start']} AND ".$value['end']." AND `continue`>0
                    GROUP BY `day`,`hall_id`;";
                $cinema_count1 = M()->db($type)->query($sql); //单个影院每个影厅每天统计数据
                foreach($cinema_count1 as $key=>$row1){
                    $row1['day'] = strtotime($row1['day']);
                    $cinema_count1[$key]['day']= $row1['day'];
                    $cinema_count1[$key]['ctime']=NOW_TIME;
                    $cinema_count1[$key]['utime']=NOW_TIME;
                    $cinema_count1[$key]['hall_num'] = $res['coutInfo'][$row1['day']]['count'];
                    $cinema_count1[$key]['price'] = $price;
                }
                $sql = 'DELETE FROM '.trueTab('OrgPlayCount_'.$row)." WHERE `day` BETWEEN {$value['start']} AND {$value['end']};";
                M()->db($type)->execute($sql); //删除旧的影厅统计
                M()->db($type)->table(trueTab('OrgPlayCount_'.$row))->addAll($cinema_count1); //影厅统计数据入库
                $sql = 'SELECT `day`,
                    SUM(`play_count`) AS `play_count`,
                    SUM(`play_half_billing`) AS `play_half_billing`,
                    SUM(`play_all_billing`) AS `play_all_billing`,
                    SUM(`total_price`) AS `total_price`,
                    SUM(`pay`) AS `pay`, `price`,`hall_num`  FROM '.trueTab('OrgPlayCount_'.$row)
                    ." WHERE `day` BETWEEN {$value['start']} AND {$value['end']} GROUP BY `day`;";
                $cinema_count2 = M()->db($type)->query($sql);
                foreach($cinema_count2 as $key=>$row1){
                    $cinema_count2[$key]['ctime']=NOW_TIME;
                    $cinema_count2[$key]['utime']=NOW_TIME;
                    $cinema_count2[$key]['cinema_id']=$row;
                    $cinema_count2[$key]['type'] = $type;
                }
                //删除旧统计数据
                $sql = 'DELETE FROM '.trueTab('OrgPlayCount').' WHERE cinema_id='.$row." AND `day` BETWEEN {$value['start']} AND {$value['end']};";
                M()->db(0)->execute($sql);
                $cinema_count = array_merge($cinema_count,$cinema_count2);
            }
            $film_count = array_merge($film_count,$this->countFilm($type,$row,$nearTime,$now)); //统计每日每个影院播放的影片
            //修改已统计数据状态
            $sql = 'UPDATE '.trueTab('OrgPlay_'.$row)." SET `status`=2
            WHERE `status`<>2 AND `play_start` BETWEEN {$near['play_start']} AND {$now}";
            M()->db($type)->execute($sql); //统计到前一天的数据
            $sql = 'SELECT * FROM '.trueTab('OrgPlay_'.$row).' WHERE `status`<>2 LIMIT 1';
            $flog = M()->db($type)->query($sql);
            !$flog[0] AND  D('Common/Cache','Logic')->HDEL(C('DATA_KEY.CHANGE_CINEMA'),$host_name); //统计完成,清除需要统计的标记
        }
        $cinema_count AND M()->db(0)->table(trueTab('OrgPlayCount'))->addAll($cinema_count); //影院统计数据入库
        $film_count AND M()->db(0)->table(trueTab('OrgFilmCount'))->addAll($film_count);
    }

    /* 日志文件创建 */
    private function createLog(){
        $dir = str_replace('ThinkPHP/','',THINK_PATH).'Uploads/KmiLog'; //日志目录
        $dir = preg_replace('/([\\\])/','/',$dir); //兼容Windows环境
        is_dir($dir) or mkdir($dir, 0777, true); //创建日志目录
        if(!is_file($dir.'/log.txt')){
            file_put_contents($dir.'/log.txt', '');
        }
        $this->log = $dir.'/log.txt';
    }

    //同步影片点播次数
    public function syncVideoCount(){
        if(!$this->videoCount)return true;
        $data['class'] = 'Film';
        $data['method'] = 'setFilmPlayCount';
        $data['play_source'] = 'kmi';
        $data['film_data'] = $this->videoCount;
        callWebInterfaceData($data);
    }

    /**
     * 获取免费配置信息
     */
    public function getFreeInfo(){
        $db = C('DB_TYPE').'://'.C('DB_USER').':'.C('DB_PWD').'@'.C('DB_HOST').':'.C('DB_PORT').'/data_center';
        $model = M()->db('data_center',$db); //数据中心库
        $map['key'] = array(
            'in',
            array('free_cinemas','type_free_videos')
        );
        $data = $model->table(trueTab('configs'))
            ->where($map)
            ->where('deleted_at IS NULL')
            ->field('key,value')
            ->select();
        foreach($data as $row){
            $this->configs[$row['key']] = json_decode($row['value'],true);
        }
    }

    /* 播放计费统计;每天5点钟统计 */
    public function billing(){
        //$this->getFreeInfo();
        $this->handleDataCenter(); //顺网播放记录脚本处理
        $this->timediff = strtotime('1970-01-01');
        $this->createLog(); //创建日志文件
        $this->handHall(); //取出缓存数据,写入数据库
        $this->hallCount(); //统计影厅增量
        $this->handPlay(); //取出缓存点播数据,写入数据库
        $this->countCinema();//统计每个影院每天的消费记录

        $this->syncVideoCount();//同步影片点播次数
        $this->syncLastPlayTime(); //同步影院最近播放时间
        dump_exit('统计完成');
    }

    public function getFilms(){
        $films = array();//影片信息
        $keys = D('Common/Cache','Logic')->getKeys(C('DATA_KEY.SYNC_DATACENTER').':ONLINE'); //获取所有影院的缓存数据
        foreach($keys as $rkey){
            $data = D('Common/Cache','Logic')->HGETALL($rkey); //获取所有缓存数据
            foreach($data as $key=>$row){
                $row = json_decode($row,true);
                $films[$row['save_name']] = 1; //去除重复的影片
            }
        }
        $films = array_keys($films);
        if(!$films){
            return [];
        }
        //加密参数
        $data = array(
            'token' => 'micro_ticket_net',
            'time' => NOW_TIME,
        );
        $des_str = \TripleDES::encode( json_encode( $data )  , 'iuflas82iuflas82', 'vstle7w4vstle7w4' );

        $post_param['token'] = rawurlencode( $des_str );
        $post_param['save_name'] = json_encode($films);
        $param['method'] = 'post';//post方式
        $param['post_data'] = $post_param;//要拼接的参数
        $map['k'] = 'video_host';
        $video_host = M('config')->where($map)->find()['v'];
        $url = $video_host.'/Api/Video/getVideoInfoWithSavename';
        $video_str = syncLocalContents($url, $param);
        $video = json_decode($video_str, true)?:[];

        return $video;
    }

    /**
     * 缓存公共主机
     * @param $host_name
     * @return mixed
     */
    public function getCommonCinema($host_name){
        $host_name = strtoupper(explode('-',$host_name)[0]);
        if(!isset($this->CommonCinema[$host_name])){
            //查询公共主机信息
            $this->CommonCinema[$host_name] = $this->getCinema($host_name);
            //获取公共主机最大播放记录ID
            $this->CommonCinema[$host_name]['max_id'] = $this->CommonCinema[$host_name] ?
            intval($this->connect($this->CommonCinema[$host_name]['type'])
                ->query('SELECT MAX(`id`) AS `max_id` FROM mt_org_play_'.$this->CommonCinema[$host_name]['id'])[0]['max_id']):0;

        }
        return $this->CommonCinema[$host_name];

    }

    /**
     * 处理顺网数据
     */
    public function handleDataCenter(){
        $keys = D('Common/Cache','Logic')->getKeys(C('DATA_KEY.SYNC_DATACENTER').':ONLINE'); //获取所有影院的缓存数据
        $films = $this->getFilms();//影片信息
        //dump_exit($keys);
        foreach($keys as $rkey){
            $is_common = true; //公共主机
            //主机host_name
            $host_name = str_replace(C('DATA_KEY.SYNC_DATACENTER').':ONLINE:','',$rkey); //获取数据的host_name
            $cinema = $this->getCinema($host_name)?:$this->getCommonCinema($host_name); //查询主机信息

            if(!isset($cinema['max_id'])){
                if(!isset($this->CommonCinema[strtoupper(explode('-',$host_name)[0])])){
                    //不是公共主机
                    $is_common = false;
                }
                $cinema['max_id'] = $cinema['type'] ? intval(M()->db($cinema['type'])
                    ->query('SELECT MAX(`id`) AS `max_id` FROM mt_org_play_'.$cinema['id'])[0]['max_id']):0;
            }

            $params = array();
            $params['host_name'] = $cinema['host_name']?:$host_name; //主机
            $params['tab'] = 'OrgPlay'; //表名
            $data = D('Common/Cache','Logic')->HGETALL($rkey); //获取所有缓存播放数据
            foreach($data as $key=>$row){
                $row = json_decode($row,true);
                $film = $films[$row['save_name']];
                if(!$film){
                    continue;
                }
                //查询影厅是否存在
                $cinema['id'] AND $this->checkHall($cinema,$row['mac'],$row['ctime']); //影院不存在时,不添加影厅
                $row['hall_id'] = $this->hall[$cinema['id']]['list'][$row['mac']]['id']?:$row['mac'];
                //查询播放记录是否存在
                $old = $cinema['id'] ? M('OrgPlay_'.$cinema['id'])
                    ->db($cinema['type'])
                    ->where(['video_id'=>$film['id'],
                        'hall_id'=>$row['hall_id'],
                        'play_start'=>$row['ctime'],
                        'video_path'=>$is_common?$row['key']:''
                    ])->find():null;

                if($is_common){
                    if($old){
                        $id = $old['id'];
                    }else{
                        $this->CommonCinema[$cinema['host_name']]['max_id'] = ++$this->CommonCinema[$cinema['host_name']]['max_id'];
                        $id = $this->CommonCinema[$cinema['host_name']]['max_id'];
                    }
                }else{
                    if($old){
                        $id = $old['id'];
                    }else{
                        $cinema['max_id'] = ++$cinema['max_id'];
                        $id = $cinema['max_id'];
                    }
                }

                $params['list'][] = array(
                    'id'=>$id,
                    'video_id'=>$film['id'],
                    'file_name'=>$film['file_name'],
                    'time'=>$film['time'],
                    'hall_id'=>$row['hall_id'],
                    'play_start'=>$row['ctime'],
                    'play_end'=>$row['utime'],
                    'play_location'=>0,
                    'video_path'=>$row['key'],
                    'utime'=>NOW_TIME,
                    'ctime'=>NOW_TIME,
                    'status'=>1,
                    'custom'=>$row['custom']?:''
                );
                D('Common/Cache','Logic')->HDEL($rkey,$key); //删除旧数据
            }
            //检查影院
            if($is_common && $cinema['id']){
                $old_cinema = D('CinemaHostUpload')->where(['host_name'=>$host_name])->find();
                //添加下属影院
                if(!$old_cinema){
                    D('CinemaHostUpload')->add([
                        'host_name'=>$host_name,
                        'type'=>$cinema['type'],
                        'create_time'=>NOW_TIME,
                        'update_time'=>NOW_TIME,
                        'last_play_time'=>$row['utime']
                    ]);
                }
            }
            D('Common/ApiLog','Logic')->syncTab($params);
        }
        //刷入影厅数据
        $this->pushHall();
    }

    public function pushHall(){
        foreach($this->hall as $key=>$row){
            D('Common/ApiLog','Logic')->syncTab($row);
            unset($this->hall[$key]);
        }
    }

    /**
     * 影片信息查询
     * @param $id
     * @return mixed
     */
    public function getVideoInfo($id){
        if(!$this->video[$id]){
            $this->video[$id] = M('video')->db(0)->field('id,file_name,time')->find($id);
        }
        return $this->video[$id];
    }



    /**
     * 检查影厅并创建
     * @param $cinema_id
     * @param $mac
     * @param $play_start
     */
    public function checkHall($cinema,$mac,$play_start){
        if($this->hall[$cinema['id']]['list'][$mac]){
            $this->hall[$cinema['id']]['list'][$mac]['ntime'] = $play_start;
            return ;
        }
        $map['cinema_id'] = $cinema['id'];
        $sub_id = D('OrgHall')->where($map)->max('sub_id')?:0;
        $map['sn'] = $mac;
        $hall = D('OrgHall')->where($map)->find();

        //不存在屏幕,创建屏幕
        if(!$hall){
            $row = array();
            $row['cinema_id'] = $cinema['id'];
            $row['sub_id'] = ++$sub_id;
            $row['sn'] = $mac;
            $row['cost'] = 1;
            $row['ntime'] = $play_start;
            $row['ctime'] = $row['utime'] = NOW_TIME;
            $row['status'] = 1;
            D('OrgHall')->add($row);
            $hall = D('OrgHall')->where($map)->find();
        }else{
            //修改屏幕使用时间
            $hall['ntime'] = $play_start;
            ++$hall['cost'];
        }
        $hall = ['id'=>$hall['sub_id']]+$hall;
        $hall['status'] = 1;
        unset($hall['sub_id']);
        unset($hall['cinema_id']);
        $this->hall[$cinema['id']]['list'][$mac] = $hall;
        $this->hall[$cinema['id']]['host_name'] = $cinema['host_name'];
        $this->hall[$cinema['id']]['tab'] = 'OrgHall';
    }

    public function countFilm($type,$cinema_id,$time,$end){
        //欢乐影盟不统计
        if($type==5){
            return true;
        };
        //清除旧的统计记录
        $sql = "DELETE FROM ".trueTab('OrgFilmCount')." WHERE cinema_id={$cinema_id} AND `day`>={$time};";
        M()->db(0)->execute($sql);
        $time_now = NOW_TIME;
        //按影片统计播放记录
        $sql = "SELECT
                    UNIX_TIMESTAMP(FROM_UNIXTIME(play_start, '%Y-%m-%d')) AS `day`,
                    video_id,
                    '{$cinema_id}' AS cinema_id,
                    {$time_now} AS `ctime`,
                    {$time_now} AS `utime`,
                  SUM(play_end-play_start>={$this->billing_time}) AS `play_billing`,
                  SUM(play_end-play_start<{$this->billing_time}) AS `play_free`
                FROM
                    ".trueTab('OrgPlay_'.$cinema_id)."
                WHERE
                    `play_start` >= {$time} AND `play_start`<={$end} AND `continue`>0
                GROUP BY video_id,`day`;";
        //dump_exit(M()->db($type)->query($sql));
        $count = M()->db($type)->query($sql);
        return $count ? $count : array();
    }

    /**
     * 将redis里的大数据一次性同步到数据表中
     * 参数: $model 数据模型,用于切库
     *      $redis_key 缓存数据的键(队列)
     *      $table 同步到的数据表
     *      $path 暂存文件路径(相对路径)
     *      $file 暂存文件名
     */
    protected function syncBigData($model,$redis_key,$table,$path,$file){
        $dir = str_replace('ThinkPHP/','',THINK_PATH).$path; //影厅缓存数据目录
        $dir = preg_replace('/([\\\])/','/',$dir); //兼容Windows环境
        is_dir($dir) or mkdir($dir, 0777, true); //数据文件存放目录
        is_dir($dir.'/error') or mkdir($dir.'/error', 0777, true); //错误数据存放目录
        $data = D('Common/Cache','Logic')->LRANGE($redis_key,0,-1); //获取所有缓存数据
        $result = array(); //数据结果
        $error = array(); //错误数据
        $flog = $res = true; //程序执行成功标记
        foreach($data as $params){
            $params = json_decode($params,true);
            $cimema_id = D('Common/CinemaHost')->getIdByName($params['host_name']); //查询院线主机信息
            $id = $cimema_id ? $cimema_id : $params['host_name']; //影院ID
            foreach($params['list'] as $key => $row){
                if(!$table){ //播放日志处理
                    $row['continue'] = $row['play_end'] - $row['play_start']; //播放持续时长
                    $row['file_name'] = str_replace(',','，',$row['file_name']); //替换特殊字符
                    $custom = json_decode(str_replace('&quot;','"',$row['custom']),true);
                    //付费计算
                    if(in_array($id,$this->configs['free_cinemas']) || //免费影院
                        in_array($row['video_id'],$this->configs['type_free_videos']['agent_'.$model]['value'])){ //免费影片
                        $row['pay'] = 0;
                    }elseif($row['continue']<=C('BILLING_BASE') || $custom['type']=='preview'){ //不计费
                        if($model==3){//KMI价格
                            $row['pay'] = 0; //当日计费金额
                        }else{
                            $row['pay'] = 1; //当日计费金额设为1
                        }
                    }elseif($row['continue']/$row['time']>C('HALF_PRICE')){ //全价计费
                        $price = $this->getPrice($row['play_start'],$model);
                        $row['pay'] = $price['price'];
                    }else{ //半价计费
                        $price = $this->getPrice($row['play_start'],$model);
                        $row['pay'] = $price['price']/2;
                    }

                    unset($row['custom']);
                    $row['sn'] = $custom['sn'] ? $custom['sn'] : '';
                    $row['type'] = $custom['type']=='preview' ? 2 : 1;
                    $params['list'][$key] = implode(',',$row);
                    $row['status']==1 AND $model==3 AND $this->videoCount[$row['video_id']] += 1; //KMI统计影片点播次数
                }else{
                    $params['list'][$key] = $id.','.implode(',',$row);
                }
            }
            if(!$cimema_id){ //错误数据
                $params['list'] AND $error[] = implode("\r\n",$params['list']);
            }else{ //正确数据
                $params['list'] AND $result[] = implode("\r\n",$params['list']);
            }
        }
        if($result){ //正确数据处理
            $file_ok = $dir.'/'.$file.'.txt'; //生成数据文件
            file_put_contents($file_ok, implode("\r\n",$result))===false AND $flog = false; //将数据存入文件
            unset($result); //释放内存
            $table OR $table = 'OrgPlay_'.$id; //播放日志表
            $sql = "LOAD DATA INFILE '".$file_ok."' REPLACE INTO TABLE ".trueTab($table)." FIELDS TERMINATED BY ',';";
            $res = M()->db($model)->execute($sql);
            if($res===false){
                file_put_contents($this->log, '数据入库失败:'.$file_ok."\r\n",FILE_APPEND);
            }else{
                $model AND D('Common/Cache','Logic')->HSET(C('DATA_KEY.CHANGE_CINEMA'),$params['host_name'],$id); //修改表记录标记
                unlink($file_ok);//删除操作成功文件
            }
        }
        if($error){
            $file = $dir.'/error/'.$file.'.txt'; //生成数据文件
            file_put_contents($file, implode("\r\n",$error))===false AND $flog = false;
            file_put_contents($this->log, '错误数据:'.$file."\r\n",FILE_APPEND);
        }
        $flog AND $data AND D('Common/Cache','Logic')->del($redis_key); //清除缓存数据
        return $res;
    }

    /**
     * 影厅数据批量入库
     */
    protected function handHall(){
        return $this->syncBigData(0,C('DATA_KEY.SYNC_TAB').':OrgHall','OrgHall','Uploads/OrgHall',date('Y-m-d'));
    }

    protected function getCinema($host_name){
        $map['host_name'] = $host_name;
        return M()->db(0)->table(trueTab('CinemaHost'))->where($map)->find();
    }

    /**
     * 通过host_name获取影院类型
     */
    protected function getCinemaType($host_name){
        $map['host_name'] = $host_name;
        $type = M()->db(0)->table(trueTab('CinemaHost'))->where($map)->field('type')->find();//查询影院类型
        return $type['type'];
    }

    //初始化分库链接
    protected function connect($type){
        if(!$this->DbType[$type]){ //初始化分库链接
            $db = C('DB_TYPE').'://'.C('DB_USER').':'.C('DB_PWD').'@'.C('DB_HOST').':'.C('DB_PORT').'/'.C('DB_CONFIG'.$type);
            $this->DbType[$type] = M()->db($type,$db);
        }
        return $this->DbType[$type];
    }

    /**
     * 播放记录批量入库
     */
    protected function handPlay(){
        $keys = D('Common/Cache','Logic')->getKeys(C('DATA_KEY.SYNC_TAB').':OrgPlay'); //获取所有影院的缓存数据
        foreach($keys as $rkey){
            $host_name = str_replace(C('DATA_KEY.SYNC_TAB').':OrgPlay:','',$rkey); //获取数据的host_name
            $type = $this->getCinemaType($host_name);
            $this->connect($type); //初始化分库链接
            $this->syncBigData($type,$rkey,false,'Uploads/OrgPlay/'.date('Y-m'),date('d-').$host_name);
        }
    }
    /**
     * 通过影厅数量获取当前单价
     */
    protected function hallNumToPrice($rule,$total){
        foreach($rule as $k=>$value){
            $condition = explode('-',$k);
            if(count($condition)==2 && $condition[0]<=$total && $total<=$condition[1]){
                $price = $value; //当天单价
                break;
            }elseif(count($condition)==1){
                $price = $value;
            }
        }
        return $price;
    }

    /**
     * 统计影厅数据
     */
    protected function hallCount(){
        $hall_total = M()->query('SELECT COUNT(*) AS `count` FROM '.trueTab('OrgHall').';'); //当前影厅总数
        $hall_total = $hall_total[0]['count'];
        $count_total = M()->query('SELECT SUM(`total`) as `total` FROM (SELECT MAX(`total`) as `total` FROM '.trueTab('OrgHallCount').' GROUP BY type) as a');//查询最后统计的影厅数
        $count_total = $count_total[0]['total'];
        if($hall_total!=$count_total){ //影厅有变动重新统计影厅增量数据
            $sql = 'SELECT
                       FROM_UNIXTIME(ctime,"%Y-%m-%d") AS `day`,
                       COUNT(*) AS day_total,
                       `type`
                    FROM mt_org_hall,mt_cinema_host
                    WHERE mt_org_hall.cinema_id=mt_cinema_host.id
                    GROUP BY `type`,`day`
                    ORDER BY `type`,`day`';
            $hall_count = M()->query($sql); //影厅增量数据
            $total = 0;
            $type = 0;
            foreach($hall_count as $key=>$row){
                !$type AND $type=$row['type']; //类型初始值
                if($type!=$row['type']){
                    $total=0; //切换到下一类型,初始统计影厅数
                    $type = $row['type'];
                }
                $total += $row['day_total'];
                switch($type){
                    case 3:
                        $price = $this->hallNumToPrice( C('BILLING_RULE'.$type),$total); //kmi影院单价获取
                        break;
                    default:
                        $price = 0; //默认单价
                        break;
                }

                $hall_count[$key]['day'] = strtotime($row['day']); //统计日期
                $hall_count[$key]['total'] = $total; //当天之前总影厅数
                $hall_count[$key]['price'] = $price; //当日计费单价
                $hall_count[$key]['status'] = 1; //状态
            }
            M()->startTrans();
            M()->execute('DELETE FROM '.trueTab('OrgHallCount'));
            $res = M()->table(trueTab('OrgHallCount'))->addAll($hall_count);
            if($res===false){
                M()->rollback();
            }else{
                M()->commit();
            }
            return $res;
        }
        return true;
    }

    /**
     * 创建kmi影院数据表
     */
    public function createKmiCinema($cinema_id,$type){
        if(!$cinema_id){
            return false;
        }

        $this->connect($type);
        $sql = "CREATE TABLE `".C('DATA_CACHE_PREFIX')."org_play_count_".$cinema_id."` (
              `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
              `day` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '日期',
              `hall_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '影厅ID',
              `play_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '点播总次数',
              `play_half_billing` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '收费半价点播次数',
              `play_all_billing` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '收费全价点播次数',
              `price` double unsigned NOT NULL DEFAULT '0' COMMENT '当天点播单价',
              `hall_num` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '当日屏幕数',
              `pay` double unsigned NOT NULL DEFAULT '0' COMMENT '当天结算价格',
              `total_price` double unsigned NOT NULL DEFAULT '0' COMMENT '当天总价',
              `ctime` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间',
              `utime` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '修改时间',
              `status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态:0-已删除,1-正常',
              PRIMARY KEY (`id`),
              KEY `day` (`day`),
              KEY `hall_id` (`hall_id`),
              KEY `status` (`status`),
              KEY `pay` (`pay`)
            ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT='影院每天点播统计表';";
        M()->db($type)->execute($sql);
        $sql = "CREATE TABLE `".C('DATA_CACHE_PREFIX')."org_play_".$cinema_id."` (
              `id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '院线记录ID',
              `video_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '影片ID',
              `file_name` varchar(255) NOT NULL DEFAULT '' COMMENT '影片名称',
              `time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '影片总时长',
              `hall_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '影厅唯一标示',
              `play_start` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '影片播放开始时间',
              `play_end` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '影厅播放结束时间',
              `play_location` float unsigned NOT NULL DEFAULT '0' COMMENT '结束播放位置',
              `video_path` varchar(255) NOT NULL DEFAULT '' COMMENT '影片播放路径',
              `utime` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '修改时间',
              `ctime` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '记录创建时间',
              `status` tinyint(3) unsigned NOT NULL DEFAULT '1' COMMENT '状态:0-已删除,1-正常,2-已统计,3-更新数据',
              `continue` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '持续时长',
              `pay` double NOT NULL DEFAULT '0' COMMENT '计费价格',
              `sn` varchar(255) NOT NULL DEFAULT '' COMMENT 'kmi端透明参数',
              `type` tinyint(4) DEFAULT '1' COMMENT 'kmi端透明参数:1-单片付费,2-预览',
              PRIMARY KEY (`id`),
              KEY `status` (`status`),
              KEY `play_start` (`play_start`),
              KEY `hall_id` (`hall_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='三方合作影院点播记录';";
        M()->db($type)->execute($sql);
        return true;
    }

    //获取影片点播次数
    public function getFilmPlayCount(){
        $data['class'] = 'Film';
        $data['method'] = 'getFilmPlayCount';
        $data['play_source'] = 'kmi';
        $res = callWebInterfaceData($data);
        return $res['result'];
    }

    /**
     * 同步最近使用影院
     */
    public function syncLastPlayTime(){
        $sql = 'SELECT cinema_id AS `id`,MAX(ntime) AS last_play_time FROM '.trueTab('org_hall').' WHERE `status`=1 GROUP BY cinema_id';
        $data = M()->db(0)->query($sql);
        if(!$data){return true;}
        foreach($data as $row){
            if(D('Common/CinemaHost')->save($row)===false){return false;};
        }
        $sql = 'UPDATE '.trueTab('org_hall').' SET `status`="2" WHERE `status`=1';
        return M()->db(0)->execute($sql);
    }

    /**
     * Kmi播放计费规则调整，重新计算
     */
    public function refreshKmiBilling(){
        $type = 3;
        $sql = 'SELECT id, host_name,`type` FROM '.trueTab('cinema_host').' WHERE host_name!="" AND `type`!='.$type;
        //$sql = 'SELECT id, host_name FROM '.trueTab('cinema_host').' WHERE `id`=297';//4703
        $data = M()->db(0)->query($sql);
        foreach($data as $v){
            D('Common/Cache','Logic')->HSET(C('DATA_KEY.CHANGE_CINEMA'),$v['host_name'],$v['id']);
            $table = 'OrgPlay_'.$v['id'];
            //$update1 = 'UPDATE '.trueTab($table).' SET `status`=1, `pay`=0 where `status`<>1';
            $update1 = 'UPDATE '.trueTab($table).' SET `status`=1, `pay`=1 where `pay`<>1';
            var_dump($update1);
            $this->connect($v['type']);//初始化分库链接
            var_dump(M()->db($v['type'])->execute($update1));
            //$update2 = 'UPDATE '.trueTab($table).' SET `pay`=10 where (`play_end`-`play_start`>=900)';
            //var_dump($update2);
            //var_dump(M()->db($type)->execute($update2));
        }
    }

}
